<?php
namespace jy_dayfee;
defined('BY_JYA') or exit('error');
/*
	品牌代理分红计算
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$isopen=intval($this->setting['isopen']);
		if(!$isopen){
			return;
		}
		//file_put_contents(ROOT_D.'/1.txt','create');
		$this->model('member')->update_agent_level($order['mid']);
		$this->order=$order;
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'commission_money'=>0,
			'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		//直推收益
		$fromuser=pdo_getcolumn('core_members',array('id'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']),'fromuser');
		if($fromuser){
			$member=$this->get('member',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
		}
		if($member['status']==1){
			$this->create_commission($member);
		}
		$member2=$this->get('member',array('mid'=>$member['fromuser'],'uniacid'=>$_SESSION['uniacid']));
		if($member2['status']==1){
			$this->create_commission($member2,1);
		}
		//带货收益
		//file_put_contents(ROOT_D.'/1.txt',$order['merchid'].'api_data'.$order['api_data']);
		$api_data=json_decode($order['api_data'],true);
		if(!$order['merchid'] && $api_data['dhmerchid']){
			$this->daihuo_commission($order,$api_data['dhmerchid']);
		}
		//自购赠送
		$this->buy_song($order);
		//生成分销订单
		if($this->commission_order['isarea']){
			$indata=$this->commission_order;
			unset($indata['isarea']);
			$this->insert('order',$indata);
		}
		return true;
	}
	public function buy_song($order=array()){
		foreach($order['goods'] as $goods){
			$goodsset=$this->get('goods',array('goods_id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']));
			$goods['total']=$goods['total']?:1;
			//file_put_contents(ROOT_D.'/1.txt',$goodsset['gnum']);
			if(intval($goodsset['gnum'])>0){
				$gnum=$goodsset['gnum']*$goods['total'];
				$this->model('member')->member_feelog($order['mid'],'g_fee',$gnum,true,2);
				$this->model('task')->g_sffee($order['mid'],$gnum);
			}
			if(intval($goodsset['anum'])>0){
				$anum=$goodsset['anum']*$goods['total'];
				$this->model('member')->member_feelog($order['mid'],'a_fee',$anum,true,1);
			}
		}
		return true;
	}
	/*
		给指定带货分红计算分红
	*/
	public function daihuo_commission($order,$dhmerchid=0){
			if(!$this->setting['is_opendh'] || !$dhmerchid){
				return false;
			}
			$mid=pdo_getcolumn('jy_merch_user',array('id'=>$dhmerchid,'uniacid'=>$_SESSION['uniacid']),'mid');
			if(!$mid){
				return false;	
			}
			$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			if($member['level_id']){
				$level=pdo_get('jy_dayfee_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$member['level_id']));
			}elseif($member['id']){
				$level=$this->plugin_setting('default_level');
			}else{
				$level=$this->setting;
			}
			$order_price=$order['price'];
			$feerate=$level['dh_pate'];
			$fee=0;
			$this->needorder=false;
			$total_lastcostprice=0;
			foreach($this->order['goods'] as $goods){
						$total_price=$goods['total_price']?:pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goods['id']),'total_price');
						$goods_commission=$this->get('goods',array('goods_id'=>$goods['goodsid']));
						if(!$goods_commission['id']){
							$this->needorder=true;
							continue;
						}
						if($goods_commission['ignore']){
							$order_price=$order_price-$goods['total_price'];
							continue;
						}
						//如果商品单独设置佣金，将减少本商品的金额
						$order_price=$order_price-$total_price;
						$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
						foreach($goods_commission['commissions'] as $gc){
							if($gc['level_id']==0){
								$dh_pate=$gc['dh_pate'];
							}
							if($gc['level_id']!=$member['level_id']){
								continue;
							}else{
								$dh_pate=$gc['dh_pate'];
								break;
							}
						}
						if(substr($dh_pate,-1)=='%'){
							$fee+=($total_price*substr($dh_pate,0,-1))/100;
						}else{
							$fee+=$dh_pate*$goods['total'];
						}
			}
			if($this->needorder && $order_price>0){
						if(substr($feerate,-1)=='%'){
							$fee+=($total_price*substr($feerate,0,-1))/100;
						}else{
							$fee+=$feerate;
						}
			}
			$remark=array(
				'order_price'=>$order['price'],
				'commission_money'=>$fee,
				'commission_per'=>$feerate,
			);
			if($fee>0){
				$this->commission_order['commission_money']+=$fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$mid,
					'merchid'=>$dhmerchid,
					'ordersn'=>$order['ordersn'],
					'money'=>$fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'level'=>2,
					'status'=>0,
				);
				pdo_insert('jy_dayfee_commission',$new_commission);
			}
	}
	/*
		直推收益
	*/
	function create_commission($agent=array(),$isjian=0){
		$buymember=$this->get('member',array('mid'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']));
		if($agent['level_id']){
			$level=pdo_get('jy_dayfee_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$agent['level_id']));
		}else{
			$level=$this->plugin_setting('default_level');
		}
		if(!$level['tui_levels'] || !$level['tui_rate']){
			$notui_rate=1;
		}
		$buymember['level_id']=$buymember['level_id']?:0;
		if(strpos($level['tui_levels'],';'.$buymember['level_id']) !==false){
		}else{
			//file_put_contents(ROOT_D.'/1.txt',$level['tui_levels'].'~~'.$buymember['level_id']);
			$notui_rate=1;
		}
		$order_price=$this->order['price'];
		$feerate=$level['tui_rate'];
		$feegrate=$level['tui_grate'];
		$feegrate2=$level['tui_grate2'];
		$fee=0;
		$gfee=0;
		$gfee2=0;
		$this->needorder=false;
        $total_lastcostprice=0;
		foreach($this->order['goods'] as $goods){
					$total_price=$goods['total_price']?:pdo_getcolumn('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$goods['id']),'total_price');
					$costprice=pdo_getcolumn('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$goods['goodsid']),'costprice');
					$total_costprice=$goods['total']*$costprice;
					$total_lastcostprice +=$total_costprice;
					$goods_commission=$this->get('goods',array('uniacid'=>$_SESSION['uniacid'],'goods_id'=>$goods['goodsid']));
					if(!$goods_commission['id']){
						$this->needorder=true;
						continue;
					}
					if($goods_commission['ignore']){
						$order_price=$order_price-$goods['total_price'];
						continue;
					}
					//如果商品单独设置佣金，将减少本商品的金额
					$order_price=$order_price-$total_price;
					$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
					foreach($goods_commission['commissions'] as $gc){
						if($gc['level_id']==0){
							$tui_rate=$gc['tui_rate'];
							$tui_grate=$gc['tui_grate'];
							$tui_grate2=$gc['tui_grate2'];
						}
						if($gc['level_id']!=$agent['level_id']){
							continue;
						}else{
							$tui_rate=$gc['tui_rate'];
							$tui_grate=$gc['tui_grate'];
							$tui_grate2=$gc['tui_grate2'];
							break;
						}
					}
					//利润计算
					if($this->setting['commissionfeetype']==2){
							$total_price -=$total_costprice;
							$total_lastcostprice -=$total_costprice;
					}
					if(substr($tui_rate,-1)=='%'){
						$fee+=($total_price*substr($tui_rate,0,-1))/100;
					}else{
						$fee+=$tui_rate*$goods['total'];
					}
					if(intval($goods_commission['anum'])>0){
						$anum=$goods_commission['anum']*$goods['total'];
						if(substr($tui_grate,-1)=='%'){
							$gfee+=($anum*substr($tui_grate,0,-1))/100;
						}else{
							$gfee+=$tui_grate*$goods['total'];
						}
						if(substr($tui_grate2,-1)=='%'){
							$gfee2+=($anum*substr($tui_grate2,0,-1))/100;
						}else{
							$gfee2+=$tui_grate2*$goods['total'];
						}
					}
		}
		if($this->needorder && $order_price>0){
					if(substr($feerate,-1)=='%'){
						$fee+=($order_price*substr($feerate,0,-1))/100;
					}else{
						$fee+=$feerate;
					}
		}
		//file_put_contents(ROOT_D.'/1.txt',$fee.'~~'.$gfee.'~~'.$gfee2);
		//直荐分润
		if($fee>0 && !$isjian && !$notui_rate){
				$this->commission_order['commission_money']+=$fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'level'=>1,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$fee,
					'remark'=>'',
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//直荐广告
		if($gfee>0 && !$isjian){
			$this->model('member')->member_feelog($agent['mid'],'a_fee',$gfee,true,12);
		}
		//间荐广告
		if($gfee2>0 && $isjian){
			$this->model('member')->member_feelog($agent['mid'],'a_fee',$gfee2,true,13);
		}
		//判断是否存在品牌代理
		$this->commission_order['isarea']=true;
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'ordersn'=>$order['ordersn']));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array(),$balance_type=0){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['fee']<=0 && $balance_type){
			if($balance_type==1){
				exi('贡献值不足，无法提现！','error');
			}else{
				exi('广告值不足，无法提现！','error');
			}
		}
		if($balance_type){
			$member=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']));
			$fromfee=$balance_type==1?$member['g_sffee']:$member['a_sffee'];
			if($balance_type==1){
				if($post['fee']>$fromfee){
					exi('贡献值不足，无法提现！','error');
				}
				$money=$post['fee'];
			}else{
				if($post['fee']>$fromfee){
					exi('广告值不足，无法提现！','error');
				}
				$level=pdo_get('jy_dayfee_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$member['level_id']));
				if(!$level['balance_tofee']){
					exi('该等级还未设置广告值提现比例，暂时不能提现！','error');
				}
				$money=$post['fee']*$level['balance_tofee']/100;
				$jifen=$post['fee']*$level['balance_tobi']/100;
			}
		}else{
			//获取可结算佣金
			$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
			if($this->setting['balance_day']){
				//结算天数
				$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
				$params['complete_time <']=$time;
			}
			$commissions=$this->getall('commission',$params);
			if(!$commissions){
				exi('没有可结算的佣金！','error');
			}
			$commission_num=count($commissions);
			$money=0;
			foreach($commissions as $commission){
				$money+=$commission['money'];
			}
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'mobile'=>$post['mobile'],
			'fromfee'=>$post['fee'],
			'jifen'=>$jifen,
			'money'=>$money,
			'type'=>$balance_type,
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		if(!$balance_type){
			foreach($commissions as $commission){
				$update=array(
					'status'=>2,
					'balancesn'=>$new_balance['balancesn'],
				);
				$this->update('commission',$update,array('id'=>$commission['id']));
			}
		}elseif($balance_type==1){
			$this->model('member')->member_feelog($mid,'g_sffee',$post['fee'],false,7);
		}elseif($balance_type==2){
			$this->model('member')->member_feelog($mid,'a_sffee',$post['fee'],false,5);
		}
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		if($balance['jifen']>0){
			cfc('core')->member_credit($balance['mid'],'credit1',$balance['jifen'],true,$this->plugin_name,'提现转积分');
		}
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,'提现打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'提现打款',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		if(!$res['payment_no'] && !$res['batch_id']){
			exi('打款到微信零钱失败！','error');
		}
		return $res['payment_no']?:$res['batch_id'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_dayfee_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}